package code20_jdbc.学生管理系统;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import code20_jdbc.JdbcUtil;

public class StudentTemplate {
	/**
	 * 查询操作
	 */
	public List<Student> query(String sql,Object...params){
		List<Student> list = new ArrayList<Student>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtil.getConnection();
			ps = conn.prepareStatement(sql);
			for(int i=0;i<params.length;i++){
				ps.setObject(i+1, params[i]);
			}
			rs = ps.executeQuery();
			while(rs.next()){
				Student s = new Student();
				s.setId(rs.getInt("id"));
				s.setName(rs.getString("name"));
				s.setAge(rs.getInt("age"));
				s.setHeight(rs.getDouble("height"));
				s.setBirthday(rs.getDate("birthday"));
				Clazz c = new Clazz();
				c.setCid(rs.getInt("cid"));
				c.setCname(rs.getString("cname"));
				c.setRoom(rs.getString("room"));
				s.setClazz(c);
				list.add(s);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JdbcUtil.close(conn, ps, rs);
		}
		return list;
	}

	/**
	 * 更新操作
	 */
	public void update(String sql,Object...params){
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtil.getConnection();
			ps = conn.prepareStatement(sql);
			for(int i=0;i<params.length;i++){
				ps.setObject(i+1, params[i]);
			}
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JdbcUtil.close(conn, ps, rs);
		}
	}

}
